import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import "./index.less"
import { Button, CheckBox, DropDownButton, LoadPanel, Popup, SelectBox, TextBox, TreeView } from 'devextreme-react';
import { CpasIcon } from '~/public/cpas-ui';
import { useModel } from 'umi';
import notify from 'devextreme/ui/notify';
import { exportDraft, exportTree } from './service';
import { DevTree, LayoutB, DevPopup } from '~/public/cpas-ui';
import { getCpasIcon } from '@/utils/icon';

const ExportTemplate = React.forwardRef((props: any, ref: any) => {

    const { initialState } = useModel('@@initialState');
    const { zcbfid, dbname, sjxmbh, zcbfName } = initialState?.curPart as API.CurPart;

    const [treeData, setTreeData] = useState<any[]>([]);
    const [visible, setVisible] = useState<boolean>(false);
    const [Url, setPathUrl] = useState<string>('');
    const [cataloguepath, setCataloguePath] = useState<string>('');

    const diaParams = useRef<any>();
    const gridRef = useRef<any>();



    const fetchData = async () => {
        const res = await exportTree({
            dbname,
        });
        console.log(res, 'res--------------');

        const resetPidData = checkAndUpdatePid(res.data);

        const filterData = filterParentNodes(resetPidData);

        setTreeData(filterData);
    };

    useEffect(() => {
        if (visible) {
            fetchData();
            setCataloguePath('');
            const pathUrl = window.main.mainObject.getAppPath();
            setPathUrl(pathUrl);
            // treeData();
        }
    }, [visible]);
    // const treeData = async () => {
    //     const res = await exportTree({
    //         dbname,
    //     });
    //     setTreeData(res);
    // };

    useImperativeHandle(ref, () => (
        {
            show: (params: any) => {
                diaParams.current = params;
                setVisible(true)
            }
        }
    ))

    function checkAndUpdatePid(data) {
        const idMap = {};

        // 构建 id 到索引的映射关系
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            idMap[item.id] = i;
        }

        // 检查每个项的 pid 是否存在
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const pid = item.pid;

            // 如果 pid 不存在，将自身的 pid 重置为 dgnd
            if (!idMap[pid] && pid !== "all") {
                item.pid = item.dgnd;
            }
        }

        return data;
    }

    function filterParentNodes(data) {
        // 创建一个集合用于存储叶子节点的id
        const leafIds = new Set();

        // 创建一个集合用于存储父节点的id
        const parentIds = new Set();

        // 遍历数据结构，记录叶子节点和父节点的id
        for (const node of data) {
            if (node.lx === 3) {
                leafIds.add(node.id);
            } else {
                parentIds.add(node.id);
            }
        }

        // 递归过滤父节点
        function filterNodes(nodes) {
            const filteredNodes = [];
            for (const node of nodes) {
                if (node.lx === 3 || leafIds.has(node.id)) {
                    filteredNodes.push(node);
                } else {
                    let children = data.filter(childNode => childNode.pid === node.id);
                    if (children.length > 0) {
                        children = filterNodes(children);
                        if (children.length > 0) {
                            node.children = children;
                            filteredNodes.push(node);
                        }
                    }
                }
            }
            return filteredNodes;
        }

        // 过滤根节点
        const filteredData = filterNodes(data);

        return filteredData;
    }


    const PhaseIcon = useCallback((node: any) => {
        console.log(node, 'node-------');
        if (node.lx === 3) {
            return (

                <div >
                    <span> {getCpasIcon(node.jdlx)}</span>{node.text}
                </div>
            );
        } else {
            return (

                <div >
                    <span> <CpasIcon type={"icon-wenjianjia"} className="phase_Icon" /></span>{node.text}
                </div>
            );
        }
    }, [])

    // const DropDownData = [
    //     {
    //         name: "导出为:底稿文档.zip(Z)"
    //     }, {
    //         name: "导出为:报告文档.zip(I)"
    //     }, {
    //         name: "导出为:底稿文件.pdf(P)"
    //     }
    // ]

    // const selsectData = [
    //     {
    //         id: 0,
    //         name: "全部"
    //     }
    // ]

    // const onCancel = () => {
    //     setVisible(false);
    // }

    // const onOk = () => {
    //     setVisible(false);
    // }

    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title='导出底稿'
                width={700}
                height={520}
                {...props}
                onHiding={() => setVisible(false)}
            // toolbarItems={[
            //     {
            //         widget: 'dxButton',
            //         toolbar: 'bottom',
            //         location: 'after',
            //         options: {
            //             text: intl('pub.cancel', '取消'),
            //             onClick: () => onCancel()
            //         },
            //     },
            //     {
            //         widget: 'dxButton',
            //         toolbar: 'bottom',
            //         location: 'after',
            //         options: {
            //             text: intl('pub.ok', '确定'),
            //             type: 'default',
            //             onClick: () => onOk()
            //         },
            //     },
            // ]}
            >
                <div style={{ width: "100%", height: "50px" }} >
                    <div style={{ width: "100%", height: "40px", display: "flex" }}>
                        <div style={{ display: 'flex', alignItems: "center", width: "100%" }} >
                            <span style={{ width: "80px" }}> 导出目录:</span>
                            <div style={{ display: 'flex', alignItems: "center", width: "100%", border: "1px solid #ddd", borderRadius: "4px" }} >
                                <TextBox value={cataloguepath ? cataloguepath : Url} style={{ border: "none" }} />
                                <span style={{ width: "25px", marginLeft: "5px" }}>
                                    <CpasIcon type='icon-daochudigao' fontSize={16}
                                        onClick={async () => {
                                            let electronComponents: any;
                                            if (window.parent) {
                                                electronComponents = window.parent.electronComponents;
                                            } else {
                                                electronComponents = window.electronComponents;
                                            }
                                            const dialog_result = await electronComponents.openDirectoryDialog();
                                            const checkFolderPath = dialog_result.filePaths[0];
                                            setCataloguePath(checkFolderPath);
                                        }}
                                    />
                                </span>
                            </div>
                        </div>
                        <div style={{ width: "13%", display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            {/* <DropDownButton
                                text='导出'
                                items={DropDownData}
                                displayExpr="name"
                                dropDownOptions={
                                    { width: '180px' }
                                }
                                onItemClick={async (e: any) => {
                                    console.log(e, "点击");
                                    console.log(cataloguepath, 'cataloguepath-----');
                                    const selectedData = gridRef.current.instance.getSelectedRowsData();
                                    if (selectedData.length <= 0) {
                                        notify("请选择您要导出的底稿模板", "waning", 2000)
                                    } else {
                                        const flitedgid = selectedData.map((item) => item.dgid);
                                        console.log(flitedgid, 'flitedgid-----');
                                        const r = await exportDraft({
                                            dbname: dbname,
                                            sjxmbh: sjxmbh,
                                            zcbfid: zcbfid,
                                            targetPath: cataloguepath,
                                            dgids: flitedgid
                                        })
                                        console.log(r, 'r---------');

                                    }
                                }}
                            /> */}
                            <Button text='导出' onClick={async () => {
                                // console.log(cataloguepath, 'cataloguepath-----');

                                const selectedDatas = (gridRef.current as any)?.treeRef.current.instance?.getSelectedNodes();
                                console.log(selectedDatas, 'selectedDatas-----------');
                                const data = selectedDatas
                                    .filter((item: any) => item.itemData.lx === 3)
                                    .map((item: any) => item.itemData.id);
                                console.log(data, 'data-----');
                                if (selectedDatas.length <= 0) {
                                    notify("请选择您要导出的底稿", "warning", 2000)
                                } else {
                                    if (data.length <= 0) {
                                        notify("请选择您要导出的底稿", "warning", 2000)
                                    } else {
                                        // const currentDate = new Date();
                                        // const year = currentDate.getFullYear();
                                        // const month = currentDate.getMonth() + 1; // 月份从0开始，所以需要加1
                                        // const day = currentDate.getDate();
                                        // const formattedDate = `${year}-${month}-${day}`;

                                        const currentDate = new Date();
                                        const year = currentDate.getFullYear();
                                        const month = (currentDate.getMonth() + 1).toLocaleString('en-US', { minimumIntegerDigits: 2 });
                                        const day = currentDate.getDate().toLocaleString('en-US', { minimumIntegerDigits: 2 });
                                        const hours = currentDate.getHours().toLocaleString('en-US', { minimumIntegerDigits: 2 });
                                        const minutes = currentDate.getMinutes().toLocaleString('en-US', { minimumIntegerDigits: 2 });
                                        const seconds = currentDate.getSeconds().toLocaleString('en-US', { minimumIntegerDigits: 2 });
                                        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                                        const formattedString = formattedDate.replace(/[- :]/g, "");

                                        const cataloguepathNew = cataloguepath + '\\' + "导出底稿_" + zcbfName + '_' + formattedString;
                                        const NewUrl = Url + '\\' + "导出底稿_" + zcbfName + '_' + formattedString;
                                        console.log(NewUrl, 'Url----');


                                        const r = await exportDraft({
                                            dbname: dbname,
                                            sjxmbh: sjxmbh,
                                            zcbfid: zcbfid,
                                            targetPath: cataloguepath ? cataloguepathNew : NewUrl,
                                            dgids: data
                                        })
                                        console.log(r);

                                        if (r) {
                                            setVisible(false);
                                            notify("导出底稿成功", 'success', 2000);
                                        } else {
                                            notify("导出底稿失败", 'error', 2000)
                                        }
                                    };
                                }
                            }} />
                        </div>
                    </div>
                    {/* 暂时隐藏 */}
                    {/* <div style={{
                        width: "100%",
                        height: "45px",
                        marginTop: "5px",
                        display: "flex"
                    }}>
                        <span style={{ display: 'flex', alignItems: 'center' }}>
                            编 制 人 :
                            <span style={{ marginLeft: "12px" }}>  <SelectBox width={100} items={selsectData} displayExpr="name" valueExpr='name' value="全部" /></span>
                        </span>

                        <span style={{ display: 'flex', alignItems: 'center', marginLeft: "8px" }}>
                            <CheckBox />
                            <span>
                                取数工式转换为内容
                            </span>
                        </span>
                        <span style={{ display: 'flex', alignItems: 'center', marginLeft: "8px" }}>
                            <CheckBox />
                            <span>
                                导出为offioe格式文件
                            </span>
                        </span>
                        <span style={{ display: 'flex', alignItems: 'center', marginLeft: "8px" }}>
                            <CheckBox />
                            <span>
                                导出附件
                            </span>
                        </span>
                    </div> */}
                </div>
                <div style={{ width: "100%", height: 'calc(100% - 50px)' }}>
                    <DevTree.Default
                        id="treeViewTest"
                        ref={gridRef}
                        selectionMode='multiple'
                        // selectByClick={true}
                        items={treeData}
                        dataStructure="plain"
                        searchMode="contains"
                        displayExpr='text'
                        parentIdExpr='pid'
                        keyExpr='id'
                        rootValue='all'
                        selectAllText="全选"
                        showCheckBoxesMode={'selectAll'}
                        searchEnabled={false}
                        itemRender={PhaseIcon}
                    />
                    {/* <DataGrid
                        className='PaperDevSortableGrid'
                        ref={gridRef}
                        dataSource={treeData}
                        width="100%"
                        height="100%"
                        id='dgid'
                        keyExpr="dgid"
                        // focusedRowEnabled={true}
                        hoverStateEnabled={true}
                        showBorders={true}
                        showColumnLines={true}
                        // 显示行的线
                        showRowLines={true}
                        selection={{
                            mode: 'multiple',
                            selectAllMode: 'allPages',
                            showCheckBoxesMode: 'onClick',
                        }
                        }
                        scrolling={{
                            mode: "virtual",
                            rowRenderingMode: "virtual",
                        }}
                        columnResizingMode="widget"
                        columnMinWidth={100}
                        // 显示斑马线
                        rowAlternationEnabled={true}
                    >
                        <Column
                            allowResizing={true}
                            allowHeaderFiltering={false}
                            caption='底稿名称'
                            dataField="dgmc" alignment='left' width={100} />
                    </DataGrid > */}
                </div>
            </Popup>
        </>
    )
});

export default ExportTemplate;
